#include "PipeClient.h"
//-----------------------------------------------------------------------------
PipeClient::PipeClient(void)
{
    FPipeName = NULL;
    LogFile = NULL;
}
//-----------------------------------------------------------------------------
DWORD PipeClient::Connect(char *Name)
{
    if(Name != NULL)
    {
        int Len = strlen(Name);
        FPipeName = (char*)malloc(Len+1);
        memset(FPipeName,0,Len+1);
        memcpy(FPipeName,Name,Len);
        WxDebug("Connessione al pipe %s",Name);
        return PIPE_CORRECT_OPERATION; 
/*        ThreadInfo.PipeName = FPipeName;
        ThreadInfo.Server = this;
        MainThread = CreateThread(NULL,BUFSIZE * 3,MainServerThread,&ThreadInfo,0, NULL);
        if(MainThread == NULL)
        {
            DWORD Err = GetLastError();
            WxDebug("Creazione server con errore %d",Err);
            return PIPE_BAD_CONNECTION;
        }   
        else
        {
            WxDebug("Server creato per il pipe %s",FPipeName);
            return PIPE_CORRECT_OPERATION;        
        }*/
    }
    return PIPE_NO_OPERATION;
}
//-----------------------------------------------------------------------------
void PipeClient::SendMsg(DWORD Recevier, void *Data, int Len)
{
    HANDLE hPipe;
    BOOL fSuccess;
    DWORD cbWritten;
    unsigned char Buf[BUFSIZE];
	char *tmp = (char*)malloc(strlen(FPipeName)+0x20);
	memset(tmp,0,strlen(FPipeName)+0x20);
	sprintf(tmp,"\\\\.\\pipe\\%s",FPipeName);    
      hPipe = CreateFile( 
         tmp,   // pipe name 
         GENERIC_READ |  // read and write access 
         GENERIC_WRITE, 
         0,              // no sharing 
         NULL,           // default security attributes
         OPEN_EXISTING,  // opens existing pipe 
         0,              // default attributes 
         NULL);          // no template file     
    if(hPipe == INVALID_HANDLE_VALUE)
    {
        cbWritten = GetLastError();
        WxDebug("SendMsg: errore in CreateFile cod. %d",cbWritten);
    }
    DWORD dwMode = PIPE_READMODE_MESSAGE; 
   fSuccess = SetNamedPipeHandleState( 
      hPipe,    // pipe handle 
      &dwMode,  // new pipe mode 
      NULL,     // don't set maximum bytes 
      NULL);
    if(!fSuccess)
    {
        cbWritten = GetLastError();
        WxDebug("SendMsg: errore in SetNamedPipeHandleState cod. %d",cbWritten);        
    }
   fSuccess = WriteFile( 
      hPipe,                  // pipe handle 
      Data,             // message 
      Len,              // message length 
      &cbWritten,             // bytes written 
      NULL);       
     if(!fSuccess)
    {
        cbWritten = GetLastError();
        WxDebug("SendMsg: errore in WriteFile cod. %d",cbWritten);        
    }     
      fSuccess = ReadFile( 
         hPipe,    // pipe handle 
         Buf,    // buffer to receive reply 
         BUFSIZE,  // size of buffer 
         &cbWritten,  // number of bytes read 
         NULL);    // not overlapped       
     if(!fSuccess)
    {
        cbWritten = GetLastError();
        WxDebug("SendMsg: errore in ReadFile cod. %d",cbWritten);        
    }         
    else
        WxDebug("SendMsg: risposta %s",(char*)Data);     
    CloseHandle(hPipe); 
}
//-----------------------------------------------------------------------------
void PipeClient::WxDebug(char *Format,...)
{
	SYSTEMTIME Now;
	GetLocalTime(&Now);
    
    char Msg[0x400];
	memset(Msg,0,0x400);
	sprintf(Msg,"[%02d/%02d/%2d-%02d:%02d:%02d.%03d]",Now.wDay,Now.wMonth,
				Now.wYear%100,Now.wHour,Now.wMinute,Now.wSecond,Now.wMilliseconds);
	
    va_list args;
    va_start (args, Format);
    vsprintf (Msg+strlen(Msg),Format, args);
    va_end (args);    
	if(LogFile != NULL)
	{
//		if(Level<=Utility->DebugLevel)
//			Utility->FormatLogToFile(LogFile,Msg);
	FILE  *out;
	out = fopen(LogFile,"a");
	int MsgLen=strlen(Msg);
	char *Temp = (char*)malloc(MsgLen+2);
	memcpy(Temp,Msg,MsgLen);
	if(Temp[MsgLen-1]!='\n')
	{
		if(Temp[MsgLen-2]!='\r')
		{
			Temp[MsgLen]='\r';
			Temp[MsgLen+1]='\n';
			MsgLen+=2;
		}
		else
		{
            Temp[MsgLen-1]='\n';
        }
    }
	else
	{
		if(Temp[MsgLen-1]=='\r')
		{
			Temp[MsgLen]='\n';
			MsgLen++;
		}
		else
		{
			memcpy(Temp+MsgLen,"\r\n",2);
			MsgLen+=2;
		}
	}
//	WriteFile(File,Temp,MsgLen,&Len,NULL);
//	CloseHandle(File);
	fwrite(Temp,MsgLen,1,out);
	fclose(out);
//	return 0;
	}    
}
//-----------------------------------------------------------------------------
PipeClient::~PipeClient(void)
{
    char *Txt = "Chiuso";
    if(FPipeName != NULL)
    {
        SendMsg(0x100,Txt,strlen(Txt));    
    }
}
//-----------------------------------------------------------------------------
bool PipeClient::PipeExist(char *Name)
{
    unsigned char In[10],Out[10];
    DWORD Read;
    BOOL fSuccess=false;
	char *tmp = (char*)malloc(strlen(Name)+0x20);
	memset(tmp,0,strlen(Name)+0x20);
	sprintf(tmp,"\\\\.\\pipe\\%s",Name); 
    HANDLE       
#ifdef UNICODE
//    fSuccess = CallNamedPipe(Utility->char_to_wchar(tmp),In,10,Out,10,&Read,10);    
     hPipe = CreateFile( Utility->char_to_wchar(tmp), GENERIC_READ |GENERIC_WRITE, 0,NULL,OPEN_EXISTING, 0, NULL);
#else	
     hPipe = CreateFile( tmp, GENERIC_READ |GENERIC_WRITE, 0,NULL,OPEN_EXISTING, 0, NULL);
#endif
    if(hPipe == INVALID_HANDLE_VALUE)
    {
        Read = GetLastError();
        WxDebug("PipeExist %d",Read);
        return false;
    }
    else
        return true;
 
}
//-----------------------------------------------------------------------------
